<?php
namespace app\api\controller\task;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use think\Request;
use app\common\task\model\TaskBoom as TaskBoom;

class Process {
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 拉取任务
     */
    public function pull() 
    {
        $post = $this->request->param();
        if (empty($post['uuid'])) return error([], '参数错误');

        $model = new TaskBoom;
        $where[] = ['device_uuid', '=', $post['uuid']];
        $where[] = ['status', '=', 0];
        $row = $model->where($where)->find();
        if (empty($row)) return error([], '任务不存在');

        // 将url转换成二维码
        $fileName = md5($row['url']) . '.png';
        $file = 'qrcode/' . $fileName;
        $qrcode = QrCode::create($row['url'])->setEncoding(new Encoding('UTF-8'))
                        ->setSize(300)
                        ->setMargin(10)
                        ->setForegroundColor(new Color(0, 0, 0))
                        ->setBackgroundColor(new Color(255, 255, 255));

        $writer = new PngWriter();
        $binary = $writer->write($qrcode);
        $binary->saveToFile($file);

        $model->where('id', $row['id'])->update(['status' => 1]);
        return success(['qrcode' => $fileName], '拉取任务成功');
    }
}